<?php

namespace Yousheng\DatabaseToolbox\Json2Migration;

use Illuminate\Console\Concerns\InteractsWithIO;
use \Illuminate\Support\Collection;

class JsonToMigration extends Parameters {
    use InteractsWithIO;
    /**
     * Array schema of the JSON file
     * 
     * @var array
     */
    public $schema;

    /**
     * Schema migration methods
     */
    protected $methods;

    /**
     * array :4 [
     * "posts" => array:6 [
     *      0 => "$table->string("name", 50)->index();"
     *      1 => "$table->enum("state", ['active', 'inactive'])->default('active');"
     *      2 => "$table->text("text");"
     *      3 => "$table->string("slug", 50)->unique();"
     *      4 => "$table->boolean("active")->default(false);"
     *      5 => "$table->foreignId("user_id")->nullable(true)->constrained()->onDelete('cascade');"
     * ]
     * "questions" => array:6 [
     *      0 => "$table->tinyInteger("difficulty")->index();"
     *      1 => "$table->enum("type", ['active', 'inactive'])->default('active');"
     *      2 => "$table->text("text");"
     *      3 => "$table->string("slug", 50)->unique();"
     *      4 => "$table->boolean("active")->default(false);"
     *      5 => "$table->foreignId("user_id")->nullable(true)->constrained()->onDelete('cascade');"
     * ]
     * "categories" => array:2 [
     *      0 => "$table->string("name", 100);"
     *      1 => "$table->string("image", 100);"
     * ]
     * "subcategories" => array:2 [
     *      0 => "$table->string("name", 100);"
     *      1 => "$table->foreignId("category_id")->constrained();"
     * ]
     * ]
     */
    
    public function __construct($jsonPath) {
        $this->setSchema($jsonPath);  // 第一步：读取json文件，生成数组
        $this->setMethods();          // 第二步：根据数组，生成迁移表中的语句(数组)
        $this->createMigrationFile(); // 第三步：生成数据迁移文件
    }
    
    private function setMethods() {
        $schemaParser = new SchemaParser($this->schema);
        $this->methods = $schemaParser->parse();
    }

    private function setSchema(String $jsonPath) {
        $jsonParser = new JsonParser($jsonPath);
        $this->schema = $jsonParser->parse();
    }

    private function createMigrationFile() {
        $migrationCreator = new MigrationCreator($this->methods);
        $migrationCreator->create();
    }
}